<template>
  <div ref="echartDom"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose} from 'vue'
import {pxToRem} from "@/utils/index";

const props = defineProps({
  pieData: {
    type: Array,
    default: () => []
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let totalValue = 0
    let tempDataList = props?.pieData?.seriesData
    for (let i = 0; i < tempDataList.length; i++) {
      totalValue += tempDataList[i].value;
    }
    let textObj = {
      name: props?.pieData?.seriesData[0]?.name,
      percentage: props?.pieData?.seriesData[0]?.percentage
    }
    let option = {
      title: {
        text: `{b|${textObj.percentage}%}\n\n${textObj.name}`,
        textAlign: 'center',
        triggerEvent: true,
        textStyle: {
          color: 'white',
          fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
          width: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 50 : 150),
          rich: {
            b: {
              align: "center",
              fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
              padding: [0, 0, 0, pxToRem(8 * props?.dialogData?.fontSizeTimes)]
            }
          },
          overflow: 'truncate', // 文本溢出时显示省略符号
          ellipsis: '...', // 使用的省略符号
        },
        tooltip: {
          show: true,
          formatter: (res) => {
            return `111`;
          }
        },
        x: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 80 : 330),
        y: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 88 : 210),
      },
      tooltip: {
        show: true,
      },
      legend: {
        top: 'center',
        right: `${10 * props?.dialogData?.fontSizeTimes}%`,
        itemHeight: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        itemWidth: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        itemGap: pxToRem(10 * props?.dialogData?.fontSizeTimes),
        width: pxToRem(20 * props?.dialogData?.fontSizeTimes),
        padding: [0, 0, 0],
        textStyle: {
          rich: {
            one: {
              width: pxToRem(70 * props?.dialogData?.fontSizeTimes),
              height: pxToRem(30 * props?.dialogData?.fontSizeTimes),
              color: 'white',
              fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
              padding: pxToRem(2 * props?.dialogData?.fontSizeTimes)
            },
            two: {
              width: pxToRem(60 * props?.dialogData?.fontSizeTimes),
              height: pxToRem(30 * props?.dialogData?.fontSizeTimes),
              color: 'white',
              fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
            },
          },
        },
        formatter: (name) => {
          let targetObj = tempDataList.find(x => x.name === name)
          const num = props?.dialogData?.fontSizeTimes === 1 ? 3: 10
          if (name.length > num) {
            // 如果名称长度超过10，则截取前5个字符和后5个字符，中间使用省略号
            return `{one|${name.substring(0, num)}...}`;
          } else {
            return `{one|${name}}`;
          }
        },
        tooltip: {
          show: true,
          formatter: (res) => {
            let targetObj = tempDataList.find(x => x.name === res.name)
            return `原因名称：${res.name}</br>事件个数：${targetObj.value}</br>占比：${targetObj.percentage}%`;
          }
        },
      },
      series: [
        {
          type: 'pie',
          radius: [`${props?.dialogData?.fontSizeTimes == 1 ? 40 : 50}%`, `${props?.dialogData?.fontSizeTimes == 1 ? 55 : 65}%`],
          center: ['30%', 'center'],
          clockwise: true,
          zIndex: 1,
          avoidLabelOverlap: true,
          label: {
            show: false,
          },
          labelLine: {
            //label线的长度
            show: false,
          },
          itemStyle: {
            normal: {
              borderWidth: pxToRem(5),
            }
          },
          tooltip: {
            show: true,
            trigger: 'item',
            formatter: '{b} {c}件 \t{d}%',
            position: (point) => {
              return [point[0], point[1]]
            }
          },
          data: props?.pieData?.seriesData
        }
      ]
    }
    option && myChart.value.setOption(option, true);

    myChart.value.on("legendselectChanged", (params) => {
      event.stopPropagation();
    });

    // 鼠标移入事件
    myChart.value.on('mouseover', function (params) {
      if (params?.componentType === 'series') {
        textObj.name = params?.data.name
        textObj.percentage = params?.data.percentage
        myChart.value.setOption({
          title: {
            text: `{b|${textObj.percentage}%}\n\n${textObj.name}`,
          }
        })
      }
    });
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  initEchart();
};

defineExpose({
  updateChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h220 {
  height: 220px;
}
.dialog-h220 {
  width: 1120px;
  height: 500px;
}
</style>